package com.gzx.spring.db.service.impl;

import java.time.LocalDateTime;

import com.alibaba.fastjson2.JSONArray;
import com.gzx.risk.core.enums.AuthStatus;
import com.gzx.risk.core.pojo.CreditAuthInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzx.risk.core.pojo.UserInfo;
import com.gzx.risk.core.utils.AESUtils;
import com.gzx.spring.db.entity.PhoneUser;
import com.gzx.spring.db.mapper.PhoneUserMapper;
import com.gzx.spring.db.pojo.ContractUserInfo;
import com.gzx.spring.db.service.PhoneUserService;

import lombok.extern.slf4j.Slf4j;

@Service
@DS("phone")
@Slf4j
public class PhoneUserServiceImpl extends ServiceImpl<PhoneUserMapper, PhoneUser> implements PhoneUserService {

	@Override
	public UserInfo getUser(long id) {
		PhoneUser phoneUser = this.getById(id);
        if (phoneUser == null) {
            return null;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(id);
		userInfo.setName(phoneUser.getName());
		userInfo.setId(phoneUser.getIdCard());
		userInfo.setPhone(AESUtils.decrypt(phoneUser.getPhone()));

        ContractUserInfo info = JSONObject.parseObject(phoneUser.getContractUserInfo(), ContractUserInfo.class);
		if (info != null) {
			if (info.getBack() != null && info.getBack().getData() != null
					&& info.getBack().getData().get("endDate") != null) {
				userInfo.setIdLastdate(info.getBack().getData().get("endDate").getData());
			}

			if (info.getFace() != null && info.getFace().getData() != null
					&& info.getFace().getData().get("sex") != null) {
				userInfo.setSex(info.getFace().getData().get("sex").getData());
			}
		} else {
			log.warn("无法找到身份证信息 name:{},id:{}", phoneUser.getName(), phoneUser.getIdCard());
		}

		return userInfo;
	}

	@Override
	public long getAccessCount(LocalDateTime startTime, LocalDateTime endTime) {
		QueryWrapper<PhoneUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.between("lastLoginTime", startTime, endTime);
		return count(queryWrapper);
	}
}
